<!-- src/views/Offboarding.vue -->
<template>
  <div class="offboarding-container">
    <!-- 页面标题栏 -->
    <div class="page-header">
      <h1>离职申请管理</h1>
      <div class="stats-container">
        <div class="stat-item">
          <span class="stat-label">总申请数</span>
          <span class="stat-value">{{ tableData.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">待处理</span>
          <span class="stat-value" style="color: #409eff">{{ pendingCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">已批准</span>
          <span class="stat-value" style="color: #67c23a">{{ approvedCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">已拒绝</span>
          <span class="stat-value" style="color: #f56c6c">{{ rejectedCount }}</span>
        </div>
      </div>
    </div>

   
<!-- 筛选工具栏 -->
<div class="filter-bar">
 <el-select 
  v-model="statusFilter" 
  placeholder="申请状态" 
  clearable 
  style="width: 160px; margin-right: 10px"
  @change="handleFilterChange"
  suffix-icon="CaretBottom"
>
  <el-option label="全部" value="" />
  <el-option label="待审批" value="0" />
  <el-option label="已通过" value="1" />
  <el-option label="已拒绝" value="2" />
</el-select>
  
<el-select 
  v-model="typeFilter" 
  placeholder="离职类型" 
  clearable 
  style="width: 160px; margin-right: 10px"
  @change="handleFilterChange"
  suffix-icon="CaretBottom"
   popper-class="custom-select-popper"
>
  <el-option label="全部" value="" />
  <el-option label="主动离职" value="1" />
  <el-option label="被动离职" value="2">
    <template #default>
    <span style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
      被动离职
      <el-icon style="color: #f56c6c; font-size: 14px;">
        <Close />
      </el-icon>
    </span>
  </template>
  </el-option>
  <el-option label="合同到期" value="3" />
</el-select>
  
  <el-input
    v-model="searchKey"
    placeholder="搜索员工ID/离职原因"
    clearable
    style="width: 240px; margin-right: 10px"
    @keyup.enter="handleFilterChange"
  >
    <template #append>
      <el-button icon="Search" @click="handleFilterChange" />
    </template>
  </el-input>
  
  <el-button 
    type="primary" 
    icon="Refresh" 
    size="small" 
    @click="resetFilter"
    style="margin-left: auto"
  >
    重置
  </el-button>
</div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        v-loading="loading"
        element-loading-text="加载中..."
        :data="filteredData"
        border
        stripe
        :row-class-name="tableRowClassName"
        style="width: 100%"
        :header-cell-style="{ 
          'background-color': '#f5f7fa', 
          'font-weight': 'bold',
          'color': '#303133'
        }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="resignId" label="申请ID" width="80" align="center" />
        <el-table-column prop="empId" label="员工ID" width="80" align="center" />
        <el-table-column prop="approverId" label="审批人ID" width="100" align="center" />
        
        <!-- 离职类型 -->
        <el-table-column label="离职类型" width="120" align="center">
          <template v-slot="scope">
            <el-tag 
              :type="scope.row.resignType === 2 ? 'warning' : 'info'"
              size="small"
            >
              {{ formatResignType(scope.row.resignType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 预计离职日期 -->
        <el-table-column label="预计离职日期" width="160" align="center">
          <template v-slot="scope">
            {{ formatDate(scope.row.expectedLeaveDate) }}
          </template>
        </el-table-column>
        
        <!-- 实际离职日期 -->
        <el-table-column label="实际离职日期" width="160" align="center">
          <template v-slot="scope">
            <span :class="{ 'text-gray': !scope.row.actualLeaveDate }">
              {{ scope.row.actualLeaveDate ? formatDate(scope.row.actualLeaveDate) : '未填写' }}
            </span>
          </template>
        </el-table-column>
        
        <!-- 申请状态 -->
        <el-table-column label="申请状态" width="120" align="center">
          <template v-slot="scope">
            <el-tag 
              :type="getStatusType(scope.row.applyStatus)"
              size="small"
              effect="dark"
            >
              {{ formatApplyStatus(scope.row.applyStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 申请时间 -->
        <el-table-column label="申请时间" width="180" align="center">
          <template v-slot="scope">
            {{ formatDateTime(scope.row.applyTime) }}
          </template>
        </el-table-column>
        
        <!-- 离职原因 -->
        <el-table-column label="离职原因" min-width="200">
          <template v-slot="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.reason || '无'"
              placement="top"
              :disabled="!(scope.row.reason && scope.row.reason.length > 15)"
            >
              <div class="reason-text">{{ scope.row.reason || '无' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
<el-table-column label="操作" width="180" align="center">
  <template v-slot="scope">
    <!-- 同意按钮 -->
    <el-button
      size="small"
      type="success"
      @click="handleAgree(scope.row)"
      :icon="Check"
      class="agree-btn"
    >
      同意
    </el-button>
    
    <!-- 拒绝按钮 -->
    <el-button
      size="small"
      type="danger"
      @click="handleReject(scope.row)"
      :icon="Close"
      class="reject-btn"
    >
      拒绝
    </el-button>
  </template>
</el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="tableData.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 无数据提示 -->
    <div v-if="filteredData.length === 0 && !loading" class="no-data">
      <el-empty description="暂无离职申请数据" />
    </div>
 
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { 
  ElMessage, ElEmpty, ElTooltip, ElTag, ElButton, 
  ElTable, ElTableColumn, ElSelect, ElOption, 
  ElInput, ElPagination 
} from 'element-plus'
// 修改图标导入方式

import { View, Refresh, Search, CaretBottom } from '@element-plus/icons-vue'
import { Check, Close   } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'


import { getResignApplyList } from '@/api/resignApply'
import { agreeResignApply, rejectResignApply } from '@/api/resignApply'
// 状态定义

const loading = ref(false)
const tableData = ref([])
const filteredData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref('')
const typeFilter = ref('')
const searchKey = ref('')
const router = useRouter()

// 页面挂载时加载数据
onMounted(() => {
  fetchResignList()
})

// 同意离职申请
const handleAgree = async (row) => {
  try {
    await agreeResignApply(row.resignId)
    ElMessage.success('已同意离职申请')
    // 刷新数据
    fetchResignList()
  } catch (error) {
    ElMessage.error(`同意失败：${error.message || '未知错误'}`)
  }
}

// 拒绝离职申请
const handleReject = async (row) => {
  try {
    await rejectResignApply(row.resignId)
    ElMessage.success('已拒绝离职申请')
    // 刷新数据
    fetchResignList()
  } catch (error) {
    ElMessage.error(`拒绝失败：${error.message || '未知错误'}`)
  }
}
// 获取离职申请列表
const fetchResignList = async () => {
  loading.value = true
  try {
    const res = await getResignApplyList()
    tableData.value = res.data || []
    // 初始化筛选
    handleFilterChange()
  } catch (error) {
    ElMessage.error(`获取数据失败：${error.message || '未知错误'}`)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 筛选数据
const handleFilterChange = () => {
  let result = [...tableData.value]
  
  // 状态筛选
  if (statusFilter.value !== '') {
    result = result.filter(item => item.applyStatus === Number(statusFilter.value))
  }
  
  // 类型筛选
  if (typeFilter.value !== '') {
    result = result.filter(item => item.resignType === Number(typeFilter.value))
  }
  
  // 搜索筛选
  if (searchKey.value) {
    const key = searchKey.value.trim().toLowerCase()
    result = result.filter(item => 
      item.empId.toString().includes(key) || 
      (item.reason && item.reason.toLowerCase().includes(key))
    )
  }
  
  filteredData.value = result
  currentPage.value = 1 // 重置页码
}

// 重置筛选条件
const resetFilter = () => {
  statusFilter.value = ''
  typeFilter.value = ''
  searchKey.value = ''
  handleFilterChange()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 计算分页后的数据（实际项目中可由后端分页）
const paginatedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(startIndex, startIndex + pageSize.value)
})

// 统计数据
const pendingCount = computed(() => {
  return tableData.value.filter(item => item.applyStatus === 0).length
})

const approvedCount = computed(() => {
  return tableData.value.filter(item => item.applyStatus === 1).length
})

const rejectedCount = computed(() => {
  return tableData.value.filter(item => item.applyStatus === 2).length
})
// 格式化日期时间
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  }).replace(/\//g, '-')
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 格式化离职类型
const formatResignType = (type) => {
  const typeMap = {
    1: '主动离职',
    2: '被动离职',
    3: '合同到期'
  }
  return typeMap[type] || `未知(${type})`
}

// 格式化申请状态
const formatApplyStatus = (status) => {
  const statusMap = {
    0: '待审批',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || `未知(${status})`
}

// 获取状态标签样式
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',   // 待审批：浅蓝/信息色
    1: 'success', // 已通过：绿色
    2: 'danger'   // 已拒绝：红色
  }
  return typeMap[status] || 'default'
}

// 行样式
const tableRowClassName = ({ row }) => {
  // 已处理的申请添加轻微透明度
  if (row.applyStatus === 2 || row.applyStatus === 3) {
    return 'processed-row'
  }
  return ''
}


</script>

<style scoped>
.offboarding-container {
  padding: 24px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面标题栏 */
.page-header {
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-header h1 {
  font-size: 20px;
  color: #1d2129;
  margin: 0;
}

.stats-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-item {
  background: #fff;
  padding: 12px 16px;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  min-width: 120px;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #86909c;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #1d2129;
}

/* 筛选工具栏 */
.filter-bar {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

/* 表格样式 */
.table-wrapper {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

::v-deep .el-table {
  border: none !important;
}

::v-deep .el-table th {
  border-bottom: 1px solid #f0f2f5 !important;
}

::v-deep .el-table td {
  border-bottom: 1px solid #f7f8fa !important;
  padding: 12px 0 !important;
}

.processed-row {
  opacity: 0.85;
}

.reason-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 8px;
  line-height: 1.5;
}

.text-gray {
  color: #86909c;
}

/* 操作按钮 */
.view-btn {
  padding: 4px 10px;
  background-color: #f0f7ff;
  color: #1890ff;
  border-color: #bbd6ff;
}

::v-deep .view-btn:hover {
  background-color: #e6f4ff;
  color: #096dd9;
  border-color: #91c2ff;
}

/* 分页样式 */
.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 12px;
  background: #fff;
  border-radius: 0 0 6px 6px;
}

/* 无数据样式 */
.no-data {
  margin: 60px 0;
  text-align: center;
  padding: 20px;
  background: #fff;
  border-radius: 6px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .offboarding-container {
    padding: 12px;
  }
  
  .stats-container {
    gap: 10px;
  }
  
  .stat-item {
    min-width: auto;
    flex: 1;
    text-align: center;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-select, .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
.agree-btn {
  margin-right: 8px;
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.reject-btn {
  background-color: #f56c6c;
  color: white;
  border-color: #f56c6c;
}
.custom-select-popper {
  max-width: 160px !important;
  min-width: 160px !important;
  z-index: 9999;
}
</style>